package com.example.nio;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * 使用Buffer和Channel输入内容
 */
public class NIOFileChannel02 {
    public static void main(String[] args) throws Exception {
        String str = "dangwen";

        File file = new File("d:\\1.txt");
        // 文件输入流，底层实现写出的流还是InputStream的实现
        // 获取FileInputStream的Channel对象，使用fileChannel和byteBuffer操作文件
        FileInputStream fileInputStream = new FileInputStream(file);
        FileChannel channel = fileInputStream.getChannel();

        // 通过文件channel将数据读取到缓存中
        ByteBuffer byteBuffer = ByteBuffer.allocate((int)file.length());
        channel.read(byteBuffer);
        System.out.println(new String(byteBuffer.array()));
        // 底层使用的是fileInputStream, 关闭fileInputStream流即可
        fileInputStream.close();

    }
}
